"""飞书API服务类"""

import logging
import requests
from typing import Dict, List, Any, Optional
import json

logger = logging.getLogger(__name__)

class FeishuAPIService:
    def __init__(self, app_id: str, app_secret: str, timeout: int = 30):
        self.app_id = app_id
        self.app_secret = app_secret
        self.timeout = timeout
        self.base_url = "https://open.feishu.cn/open-apis"
        self._access_token = None
        
    def _get_access_token(self) -> str:
        """获取访问令牌"""
        if self._access_token:
            return self._access_token
            
        url = f"{self.base_url}/auth/v3/tenant_access_token/internal"
        payload = {
            "app_id": self.app_id,
            "app_secret": self.app_secret
        }
        
        try:
            response = requests.post(url, json=payload, timeout=self.timeout)
            response.raise_for_status()
            data = response.json()
            
            if data.get("code") == 0:
                self._access_token = data["tenant_access_token"]
                return self._access_token
            else:
                raise Exception(f"获取访问令牌失败: {data.get('msg')}")
        except Exception as e:
            logger.error(f"获取访问令牌失败: {str(e)}")
            raise
            
    def _make_request(self, method: str, endpoint: str, data: Optional[Dict] = None) -> Dict:
        """发送API请求"""
        url = f"{self.base_url}/{endpoint}"
        headers = {
            "Authorization": f"Bearer {self._get_access_token()}",
            "Content-Type": "application/json"
        }
        
        try:
            if method.upper() == "GET":
                response = requests.get(url, headers=headers, timeout=self.timeout)
            else:
                response = requests.post(url, headers=headers, json=data, timeout=self.timeout)
                
            response.raise_for_status()
            result = response.json()
            
            if result.get("code") == 0:
                return result.get("data", {})
            else:
                raise Exception(f"API请求失败: {result.get('msg')}")
        except Exception as e:
            logger.error(f"API请求失败: {str(e)}")
            raise
            
    def get_table_metadata(self, app_token: str, table_id: str) -> Dict[str, Any]:
        """获取多维表格元数据"""
        endpoint = f"bitable/v1/apps/{app_token}/tables/{table_id}/meta"
        return self._make_request("GET", endpoint)
        
    def get_table_records(self, app_token: str, table_id: str, page_size: int = 100) -> List[Dict[str, Any]]:
        """获取多维表格记录"""
        endpoint = f"bitable/v1/apps/{app_token}/tables/{table_id}/records"
        params = {
            "page_size": page_size
        }
        
        all_records = []
        page_token = None
        
        while True:
            if page_token:
                params["page_token"] = page_token
                
            result = self._make_request("GET", endpoint)
            records = result.get("items", [])
            all_records.extend(records)
            
            page_token = result.get("page_token")
            if not page_token:
                break
                
        return all_records
        
    def upload_data(self, app_token: str, table_id: str, data: List[Dict[str, Any]]) -> None:
        """上传数据到多维表格"""
        endpoint = f"bitable/v1/apps/{app_token}/tables/{table_id}/records/batch_create"
        
        # 将数据分批处理，每批最多100条
        batch_size = 100
        for i in range(0, len(data), batch_size):
            batch = data[i:i + batch_size]
            payload = {
                "records": [
                    {"fields": record} for record in batch
                ]
            }
            self._make_request("POST", endpoint, payload) 